package com.jfm.jfmc.plugin.telnet.collect;

import com.jfm.jfmc.plugin.telnet.enums.ResultValue;
import com.jfm.jfmc.plugin.telnet.utils.TelnetUtil;
import com.jfm.jfmm.collector.driver.ACollectorDriver;
import com.jfm.jfmm.collector.driver.TelnetDriver;
import com.jfm.jfmm.collector.entity.collect.CheckResult;
import com.jfm.jfmm.collector.entity.collect.CollectResult;
import com.jfm.jfmm.collector.entity.collect.Param;
import com.jfm.jfmm.collector.entity.collect.param.TelnetParam;
import com.jfm.jfmm.collector.entity.collect.result.TelnetResult;
import com.jfm.jfmm.collector.enums.ResultType;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author DYang
 * @since 2024-10-12 0:27
 */
@Slf4j
@Service
public class TelnetCollect extends TelnetDriver {

    @PostConstruct
    @Override
    public void register() {
        ACollectorDriver.collectorMap.put(this.supportProtocol(), this);
    }

    @Override
    public CheckResult perCheck(Param reParam) {

        TelnetParam param = this.transformParam(reParam);

        if (param == null) return new CheckResult(ResultType.EMPTY_PARAM,"param is null");

        if (param.getHost() == null || param.getHost().isEmpty()) return new CheckResult(ResultType.EMPTY_PARAM,"host is empty");
        return null;
    }

    @Override
    public CollectResult collect(Param reParam) {
        long startTime = System.currentTimeMillis();
        TelnetParam param = this.transformParam(reParam);

        int timeout = param.getTimeout() == null ? 5000 : param.getTimeout();
        boolean available = TelnetUtil.isAvailable(param.getHost(), param.getPort(), timeout);
        long responseTime = System.currentTimeMillis() - startTime;

        TelnetResult result = TelnetResult.build()
                .delay(responseTime)
                .host(param.getHost())
                .port(param.getPort())
                .result(available ? ResultValue.SUCCESS.getValue() : ResultValue.FAIL.getValue());

        CollectResult collectResult = new CollectResult();
        collectResult.result(result)
                .startTime(startTime)
                .responseTime(responseTime)
                .protocol(this.supportProtocol());

        return collectResult;
    }


}
